/**
 * 退票查询
 */

import React, { Component } from 'react'
import {
  View, Text, StyleSheet, Image, TouchableOpacity, TextInput,StatusBar,Keyboard,TouchableWithoutFeedback
} from 'react-native'
import NavPage from '../../common/NavPage'
import SafeView from 'react-native-safe-area-view'
import moment from 'moment'
import axios from 'axios'
import qs from 'qs'
import Screen from '../../common/screen'
import Toast from 'antd-mobile/lib/toast'
import ImageResources from '../../common/ImageResources'
import FetchResources from '../../common/FetchResources'
import GetSetStorge from '../../common/GetSetStorge'
// import * as WeChat from 'react-native-wechat'
import Alipay from '../../common/Alipay'
// import BackgroundTimer from 'react-native-background-timer'
import { RouteHelper } from 'react-navigation-easy-helper'

export default class Inspect extends Component{
  constructor(props) {
    super(props)
    let { code,type} = this.props.navigation.state.params
    this.state = {
      sum:6,
      useNum:5,
      subBottom:0,
      addBottom:0,
      showInput:false,
      KeyboardShown:"",
      ticketNumber:code || '',
      mBottom:30,
      butSub:'Sub',
      butAdd:'Add',
      consumptionName:'',
      consumptionId:'',
      userId:'',
      isShowDetail:false,
      payWay:1,
      orderTime:'',
      totalPrice:'',
      singlePrice:'',
      orderState:'',
      orderData:true,
      permission:true,//验票权限
      leftNum:0,
      singlePrice:0,
      type:type||'',
      orderId:''
    
    }
  }

  componentDidMount() {
    // Toast.loading('加载中...', 0)
    let {type,ticketNumber} = this.state
    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {
        this.setState({userId:result.split('|')[0]},()=>{
          type ? this.getTicketInfo(ticketNumber,''):null
        })
      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })

  }

  componentWillMount () {  
    //监听键盘弹出事件  
    this.keyboardDidShowListener = Keyboard.addListener(  
      "keyboardDidShow",  
      this.keyboardDidShowHandler.bind(this)  
    )
    //监听键盘隐藏事件  
    this.keyboardDidHideListener = Keyboard.addListener(  
      "keyboardDidHide",  
      this.keyboardDidHideHandler.bind(this)  
    ) 
  }  
    
  componentWillUnmount() {  
    //卸载键盘弹出事件监听  
    if (this.keyboardDidShowListener != null) {  
        this.keyboardDidShowListener.remove();  
    }  
    //卸载键盘隐藏事件监听  
    if (this.keyboardDidHideListener != null) {  
        this.keyboardDidHideListener.remove();  
    }  
  }   

  //键盘弹出事件响应  
  keyboardDidShowHandler(event) {  
    this.setState({ KeyboardShown: true ,mBottom : 4 });  
  }  

  //键盘隐藏事件响应  
  keyboardDidHideHandler(event) {  
    this.setState({ KeyboardShown: false });  
  }  

  lostBlur(){  
    //退出软件盘  
    let {  sum,useNum} = this.state
    if(useNum == null || useNum == ''){
      this.setState({useNum:sum})
    }
    Keyboard.dismiss();    
  } 

  goBack() {
    RouteHelper.pop()
  }

  RefundOrder(){
    let {consumptionId,ticketNumber,userId,useNum,leftNum,singlePrice,orderId} = this.state
    let refundPrice = useNum*singlePrice
    // alert(`剩余数：${leftNum} --- 退票数：${useNum}  ---- 价格 ${refundPrice}`)
    axios.post(FetchResources.Fetch.RefundOrder,//退票接口
      qs.stringify({
        orderId,
        code:ticketNumber,
        consumptionId,
        refundUser:userId,
        leftNum,
        refundNum:useNum,
        singlePrice:refundPrice
        
      })
    ).then((response) => {
      Toast.hide()
      if(response.data.success){//查询成功
        Toast.info(`已退票${response.data.num}张,${response.data.tips}`, 2)
        this.timer = setTimeout(() => {
          this.getTicketInfo(ticketNumber,'')
        }, 2100)
        
      }else{
       
      }
    }).catch((error) => {
      // alert(JSON.stringify(error))
      Toast.hide()
    })
  }

  inspect(){
    // Toast.success('验证成功',1)
    let {consumptionId,ticketNumber,userId,useNum} = this.state
    axios.post(FetchResources.Fetch.CheckOrder,//验票接口
      qs.stringify({
        code:ticketNumber,
        consumptionId,
        checkUser:userId,
        useNum
      })
    ).then((response) => {
      Toast.hide()
      if(response.data.success){//查询成功
        if(response.data.leftNum == 0){ // 剩余可验证次数为0，表示全部已验证
          Toast.info('验证完成', 0.5)
          this.setState({useNum:response.data.leftNum,leftNum:response.data.leftNum,orderState:'已使用'})
          this.timer = setTimeout(() => {
            this.setState({isShowDetail:false,ticketNumber:''})
          }, 1100)
        }else{
          this.setState({useNum:response.data.leftNum,leftNum:response.data.leftNum,orderState:'使用中'})
          Toast.info(`剩余使用次数:${response.data.leftNum}次`, 0.5)
        }
      }else{
        Toast.info(`该验票码有效使用次数为0，请重新购票！`, 0.5)
        this.timer = setTimeout(() => {
          this.setState({isShowDetail:false,ticketNumber:''})
        }, 1100)
      }
    }).catch((error) => {
      // alert(JSON.stringify(error))
      Toast.hide()
    })
    // this.timer = setTimeout(() => {
    //   RouteHelper.navigate('TicketVerify',{consumptionName:''})
    // }, 1100)
  }

  addSubtract(type){
    this.lostBlur()
    let {leftNum,useNum } = this.state
    if(useNum == null || useNum == ''){
      this.setState({useNum:leftNum},()=>{
        this.addSub(type)
      })
    }else{
      this.addSub(type)
    }

  }

  addSub(type){
    let { leftNum,useNum  } = this.state
    if(type == 'add'){
      if(useNum < leftNum){
        this.setState({
          useNum:parseInt(useNum)+1,
          addBottom:0,
          butAdd:'AddActived',
          butSub:'Sub'
        })
        this.timer = setTimeout(() => {
          this.setState({addBottom:0,butAdd:'Add'})
        }, 300)
      }else{
        this.setState({
          butAdd:'AddDisable'
        })
      }
      
    }else{
      if(this.state.useNum>1){
        this.setState({
          useNum:parseInt(useNum)-1,
          subBottom:0,
          butSub:'SubActived',
          butAdd:'Add'
        })
        this.timer = setTimeout(() => {
          this.setState({subBottom:0,butSub:'Sub'})
        }, 300)
      }else{
        this.setState({
          butSub:'SubDisable'
        })
      }
    }
  }

  onChangeNum(useNum){
    let { sum } = this.state
    if(useNum < sum){
      this.setState({useNum})
    }
  }

  getTicketInfo(QRcodeTicketNumber,type){
    // alert(QRcodeTicketNumber)
    Toast.loading('加载中...', 0)
    let {consumptionId,ticketNumber,useNum} = this.state
    if(type == 'input'){
      if(ticketNumber == ''){
        Toast.fail('请输入卡号或扫码',0.5)
        return 
      }
      this.findOrder()
    }else{
      this.setState({ticketNumber:QRcodeTicketNumber},()=>{
        this.findOrder()
      })
    }
  }

  findOrder(){
    let {ticketNumber,userId} = this.state
    axios.post(FetchResources.Fetch.FindOrder,//验票前查询订单接口
      qs.stringify({
        code:ticketNumber,
        userId
      })
    ).then((response) => {
      Toast.hide()
      if(response.data.success){//查询成功
        let {singlePrice,leftNum,orderTime,code,totalPrice,num,payWay,consumptionName,state,consumptionId,orderId} = response.data.order
        this.setState({
          isShowDetail:true,
          consumptionName,
          payWay,
          orderTime,
          totalPrice,
          useNum:leftNum,
          leftNum,
          sum:num,
          orderState:state,
          orderData:true,
          singlePrice,
          consumptionId,
          orderId,
          permission:response.data.permission
          },()=>{})

      }else{
        this.setState({isShowDetail:false,orderData:false})
        Toast.fail(response.data.errorMessage,0.5)
      }
    }).catch((error) => {
      // alert(JSON.stringify(error))
      Toast.hide()
    })
  }

  render() {
    const dismissKeyboard = require('dismissKeyboard'); 
    let { ticketNumber, totalPrice,useNum,payWay,sum ,showInput ,mBottom,butSub,butAdd,consumptionName,isShowDetail,orderTime,orderState,permission,leftNum,orderData,type} = this.state

    return (
      <SafeView style={styles.container} forceInset={{ top: 'never' }}>
        <StatusBar
          animated={true}
          hidden={false}
          backgroundColor={'#111'}
          translucent={true}
          barStyle={'light-content'}
          showHideTransition={'fade'}
          networkActivityIndicatorVisible={true}
        />
        <TouchableWithoutFeedback onPress={this.lostBlur.bind(this)}>
        <View style={{flex:1,width:Screen.width}}>
          <NavPage goBack={this.goBack.bind(this)} title={''} refund={type&&type!='refund' ? true:''} showGoBack={true} showInspect={true} bgColor={'#F6F7F8'} />
            <Text style={{fontSize:24,color:'#111',fontWeight:'500',textAlign:'left',marginLeft:40,marginBottom:10}}>{type == 'refund' ? '验/退票' : '退票'}</Text>
            <View style={styles.inputLay}>
              <TextInput
                    placeholder="请扫描或输入..."
                    underlineColorAndroid="transparent"
                    keyboardType={'numeric'}
                    returnKeyType={'send'}
                    onSubmitEditing={this.getTicketInfo.bind(this,'','input')}
                    maxLength={20}
                    placeholderTextColor='#ccc'
                    style={styles.inputTxt}
                    value={ticketNumber}
                    defaultValue={ticketNumber}
                    onChangeText={(ticketNumber) => this.setState({ ticketNumber })}
                />
                <TouchableOpacity style={{marginRight:10}} onPress={() => RouteHelper.navigate('Qrcode', {
                callBack: (ticketNumber) => {
                  this.getTicketInfo(ticketNumber,'')
                }
              })}>
                <Image style={styles.inputCode} source={require('../../img/QRcode.png')} />
              </TouchableOpacity>

              <TouchableOpacity onPress={this.getTicketInfo.bind(this,'','input')}>
                <Image style={{width:20,height:20}} source={require('../../img/select.png')} />
              </TouchableOpacity>

            </View>

            <View style={{flex:1}}>
            
            {
              isShowDetail ?
            
              <View style={styles.goodsBox}>
                <View style={{flex:1,justifyContent: 'center',alignItems:'center',borderRadius:5}}>
                  <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center',backgroundColor:'#fff',width:Screen.width*0.9,borderRadius:5,padding:10}}>
                  
                    <View style={{height:45,flexDirection:'row',paddingHorizontal:4,borderBottomColor:'#eee',borderBottomWidth:1,borderStyle:'solid',marginBottom:10,alignItems:'center'}}>
                        
                        <View style={{height:42,flexDirection:'column',justifyContent:'flex-start'}}>
                          <View style={{flex:1,height:12,flexDirection:'row',paddingHorizontal:4,alignItems:'flex-end',justifyContent:'flex-start'}}>
                            <Text style={{fontSize:18,color:'#111'}}>{consumptionName}</Text>
                            <Text style={{fontSize:11,color:'#111',paddingHorizontal:5}}>X</Text>
                            <Text style={{fontSize:18,color:'#111'}}>{sum}</Text>
                          </View>
                          <View style={{flex:1,height:12,flexDirection:'row',paddingHorizontal:4,alignItems:'center',justifyContent:'flex-start'}}>
                            <Text style={{textAlign:'right',fontSize:11,marginHorizontal:4,fontWeight:'500'}}>总￥{totalPrice}</Text>
                            <Text style={{textAlign:'right',fontSize:11,color:'#0D9BDB',marginHorizontal:4}}>{payWay}</Text>
                            <Text style={{textAlign:'right',fontSize:11,color:'#f90',marginHorizontal:4}}>{orderState} </Text>
                          </View>
                          
                        </View>
                        <View style={{height:40,flex:1,alignItems:'flex-end',justifyContent:'flex-end'}}>
                          <Text style={{textAlign:'right',fontSize:12,color:'#ccc'}}>{orderTime}</Text>
                        </View>
                    </View>

                    <View style={{height:30,flexDirection:'row',paddingHorizontal:4}}>
                        <Text style={{flex:1,fontSize:14}}>剩余票数</Text>
                        <Text style={{flex:1,textAlign:'right',fontSize:14}}>验证数量</Text>
                    </View>

                    <View style={{flex:1,flexDirection:'row',}}>
                      <Text style={{flex:2,fontSize:32,color:'#FF9700',fontWeight:'500',paddingLeft:10}}>{leftNum}次</Text>
                      <View style={{flex:1.5,flexDirection:'row',justifyContent: 'flex-end',alignItems:'center',height:45}}>
                        <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'subtraction')} >
                            <Image style={[{width:40,height:40,padding:0,marginBottom:this.state.subBottom}]} source={useNum == 1 ?ImageResources.PayIcon['SubDisable'] : ImageResources.PayIcon[butSub]}  />
                        </TouchableOpacity>
                    
                        <TextInput
                          placeholder=""
                          underlineColorAndroid="transparent"
                          keyboardType={'numeric'}
                          returnKeyType={'next'}
                          // onSubmitEditing={() => this.refs.password.focus()}
                          maxLength={20}
                          placeholderTextColor='#ccc'
                          style={{width:32,paddingBottom:4,textAlign:'center'}}
                          value={`${useNum}`}
                          defaultValue={`${useNum}`}
                          onChangeText={(useNum) => useNum <= leftNum ? this.setState({ useNum }) : (useNum == ''||useNum == NaN ? this.setState({ useNum:leftNum }) : null) }
                          onFocus={()=>{this.setState({mBottom:4})}}
                          onBlur={()=>{this.setState({mBottom:30})}} 
                        />  
                    
                        <TouchableOpacity activeOpacity={0.8} onPress={this.addSubtract.bind(this,'add')} >
                          <Image style={[{width:40,height:40,marginBottom:this.state.addBottom}]} source={useNum == leftNum ? ImageResources.PayIcon['AddDisable'] : ImageResources.PayIcon[butAdd]}  />
                        </TouchableOpacity>
                      </View>
                    </View>
                  </View>
                </View>
              </View> : 
              null
            }
            {
              permission ? null:
              <View style={{justifyContent: 'center',alignItems:'center',marginTop:20}}>
                  <Text style={{fontSize:18}}>您没有验证该票的权限</Text>
              </View>
            }
            {
              orderData ? null:
              <View style={{justifyContent: 'center',alignItems:'center',marginTop:20}}>
                  <Text style={{fontSize:18}}>暂无此订单信息！</Text>
              </View>
            }
            </View>

            <View style={{flex:1,flexDirection:'column',justifyContent: 'center',alignItems:'center'}}>
              {
                isShowDetail && permission && leftNum > 0 ?
                <View style={{flex:1, justifyContent: 'center', alignItems: 'center',}}>
                <TouchableOpacity onPress={this.RefundOrder.bind(this)} style={{justifyContent: 'center', alignItems: 'center',}} >
                    <View style={{ justifyContent: 'center', alignItems: 'center', width: Screen.width }}>
                        <Image source={require('../../img/bg1.png')} style={{ height:92,width:298}} />
                        <View style={styles.txtLayBg}>
                            <Text style={styles.txtBg}>确认退票</Text>
                        </View>
                    </View>
                </TouchableOpacity></View> : null
              }

              {
                isShowDetail && permission && leftNum > 0 && type ?
                <View style={{flex:1,justifyContent: 'center', alignItems: 'center'}}>
                <TouchableOpacity onPress={this.inspect.bind(this)} style={{justifyContent: 'center', alignItems: 'center'}}  >
                    <View style={{ justifyContent: 'center', alignItems: 'center', width: Screen.width }}>
                      <Image source={require('../../img/bg.png')} style={{ height:92,width:298}} />
                      <View style={styles.txtLayBg}>
                          <Text style={styles.txtBg}>确认验票</Text>
                      </View>
                    </View>
                </TouchableOpacity></View> : null
              }
            </View>
          </View>
        </TouchableWithoutFeedback>
      </SafeView>
    )
  }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F6F7F8',
        alignItems: 'center',
    },
    itemNameLay: {
        alignSelf: 'flex-start',
        marginTop: 16,
        paddingHorizontal: Screen.width * 0.088,
    },
    goodsBox:{
        height:172,
        borderRadius:4,
        padding:10,
        marginTop:20
    },
    buttons:{
        fontSize: 16,
        textAlign:'center',
        width:25,
        height:25,
        borderColor:'#bbb',
        borderRadius:12.5,
        borderStyle:'solid',
        borderWidth:1,
    },
    item: {
        height:68,
        backgroundColor: '#fff',
        alignItems: 'center',
        paddingHorizontal: 10,
        marginBottom:10,
        flexDirection: 'row',
        borderRadius:5
    },
    yue: {
        padding: 20,
        alignItems: 'center'
    },
    txt: {
        borderWidth: 1,
        borderColor: '#eee',
        width: Screen.width * 0.5,
        height: 40,
        paddingHorizontal: 10,
        marginBottom: 10
    },
    icon: {
        width: 35,
        height: 30,
        marginRight: 10,
    },
    selectIcon: {
        width: 17,
        height: 17
    },
    foot: {
        height: 45,
        flexDirection: 'row',
        width: Screen.width,
        backgroundColor: '#fff'
    },
    footLeft: {
        width: Screen.width * 0.6,
        flexDirection: 'row',
        backgroundColor: '#fff',
        alignItems: 'center',
        paddingLeft: 20
    },
    footRight: {
        backgroundColor: '#52B45D',
        width: Screen.width * 0.4,
        justifyContent: 'center',
        alignItems: 'center'
    },
    inputLay: {
        width: Screen.width * 0.784,
        marginLeft:Screen.width * 0.108,
        height: 42,
        marginTop: 16,
        paddingHorizontal: 16,
        borderRadius: 21,
        borderColor: '#CDD5DC',
        borderWidth: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'white'
    },
    inputTxt: {
        height: 24,
        padding: 0,
        fontSize: 16,
        flex: 1
    },
    inputCode: {
        width: 24,
        height: 24
    },
    txtLayBg: {
        position: 'absolute',
        left:Screen.width * 0.107,
        top:0,
        width: Screen.width * 0.786,
        height: 48,
        borderRadius:24,
        justifyContent: 'center',
        alignItems: 'center',
    },    
    txtBg: {
      color: 'white',
      fontSize: 16,
      fontWeight: 'bold',
      textAlign:'center'
    },
})